import { getPlatformTypeName, getOperateModeName, isNodeIdExistInTree, isJournalPlatform } from '../resourceData';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { mapState } from 'vuex';
import { cascaderSoft } from '@/utils/tools';
import { PICK_PLATFORM } from '@/utils/const';
// api
import { platformList, getSupplierList } from '@/api/select';
import { getOperateoptions, hasResource } from '@/api/resource';
import { getDepartmentAll, getTagAll } from '@/api/config';
// 组件
import platformIcon from '@/components/Common/platformIcon';
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import filterCascader from '@/components/Common/filterCascader';
import Title from '@/components/Title';
import TagSelect from '@/components/Common/tagSelect';
// img
import signedImg from '@/assets/signStatus/signed.png';
import notSignImg from '@/assets/signStatus/notSign.png';
import cancelledImg from '@/assets/signStatus/cancelled.png';
import notSignContractImg from '@/assets/signStatus/notSign_contract.png';
import signedContractImg from '@/assets/signStatus/signed_contract.png';
import cancelledContractImg from '@/assets/signStatus/cancelled_contract.png';
export default {
  components: {
    TagSelect,
    Title,
    platformIcon,
    SelectWithUserLoad,
    filterCascader,
    selectWithoutHttp
  },
  data() {
    return {
      initCreate: true,
      fromSignAndFinished: false, // 从签约内审同步且签约流程结束
      TAG_MODULES,
      historyAccountOperation: [],
      cooperationDepartment: [],
      attributionMatrix: '',
      deptTreeList: [],
      platformDesc: '自动采集更新：账号、粉丝量',
      microTaskData: [
        { value: '是', id: 1 },
        { value: '否', id: 0 }
      ],
      microTaskTip: '',
      tips: {
        '微博': '是否挂靠飞博微任务后台',
        '抖音': '是否挂靠飞博星图后台',
        '小红书': '是否挂靠飞博蒲公英后台',
        'B站': '是否挂靠飞博花火后台',
        '快手': '是否挂靠飞博磁力聚星后台'
      },
      resourceId: '',
      loading: false,
      laodEditDataloading: false,
      platformTypeName: '',
      attributionMatrixName: '',
      platformList: [],
      defaultUserList: [],
      linkDisable: '',
      operateModeList: [],
      supplierList: [],
      accountOperationObj: {},
      attributionMatrixObj: {},
      cooperationObj: {},
      checkValue: {
        1: 'resourceName',
        2: 'resourceId',
        3: 'resourceLink'
      },
      isSave: false,
      routeParams: {},
      hasResourceData: {},
      hasResourceType: 0, // 存在已创建内容类型 1账号 2账号id 3链接
      isLinkMatch: true,
      editDefaultData: {},
      oldData: {}, // 保存接口数据，
      tagTreeList: [], // 标签数据
      supplierType: [{ value: '公司', id: 0 }, { value: '个人', id: 1 }],
      newAccountOptions: [{ value: '是', id: 1 }, { value: '否', id: 0 }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    // 监听下单平台
    hasChoosePlatformType() {
      return !!this.editResouceForm.platformType;
    },
    // 签约号
    isContract() {
      return this.editResouceForm.isContract;
    },
    isSigned() {
      return this.editResouceForm.signStatus === 1;// 已签约
    },
    // 监听合作运营方
    hasoperateMode() {
      if (!this.editResouceForm.operateMode || this.editResouceForm.operateMode.length === 0) { return false; }
      return true;
    },
    isWeixin() {
      const platformType = this.editResouceForm.platformType;
      if (this.isEdit && this.editResouceForm) {
        if (this.editResouceForm.platformTypeName === '微信') {
          return true;
        }
      }
      if (getPlatformTypeName(platformType, this.platformList) === '微信') {
        return true;
      }
      return false;
    },
    isEdit() {
      return !!this.resourceId;
    },
    accountStatusImg() {
      switch (this.editResouceForm.signStatus) {
        case 0:
          return this.isContract ? notSignContractImg : notSignImg;
        case 1:
          return this.isContract ? signedContractImg : signedImg;
        case -1:
          return this.isContract ? cancelledContractImg : cancelledImg;
      }
    },
    editResouceRules() {
      const rules = {
        resourceName: [{ required: true, trigger: 'blur', validator: this.validateTrim('请填写账号名称', 1) }],
        resourceId: [{ required: true, trigger: 'blur', validator: this.validateTrim('请填写账户ID', 2) }],
        platformType: [{ required: true, trigger: 'change', validator: this.validateEmpty('请选择所属平台') }],
        operateMode: [{ required: true, trigger: 'change', validator: this.validateNumberEmpty('请选择运营模式') }],
        accountBelong: [{ required: true, trigger: 'change', validator: this.validateEmpty('请选择账号归属') }],
        microTask: [{ required: true, trigger: 'change', validator: this.validateNumberEmpty('请选择是否挂靠') }]
      };
      const extendRules = {
        tag: [{ required: true, trigger: 'change', validator: this.validateNumberEmpty('请选择标签') }],
        'additionalKey.tagRemark': [{ required: true, trigger: 'blur', validator: this.validateEmpty('请输入内容标签') }]
      };
      return isJournalPlatform(this.editResouceForm.platformTypeName || getPlatformTypeName(this.editResouceForm.platformType, this.platformList)) ? { ...rules, ...extendRules } : rules;
    },
    // 各字段规则
    // 下单平台
    platformTypeDisabled() {
      return this.fromSignAndFinished;
    },
    // 账号
    resourceNameDisable() {
      return (!this.hasChoosePlatformType && !this.isEdit);
    },
    // 账号ID
    resourceIdDisable() {
      return (!this.hasChoosePlatformType && !this.isEdit || !this.hasRouteAuth('medium:resource:resourceIdEdit') && this.isEdit) || this.fromSignAndFinished;
    },
    // 资源链接
    resourceLinkDisable() {
      return (!this.hasChoosePlatformType && !this.isEdit) || this.linkDisable;
    },
    resourceLinkRules() {
      return (!this.linkDisable && !this.isWeixin) ? { required: true, trigger: 'blur', validator: this.validateTrim('请填写链接', 3) } : null;
    },
    // 运营模式
    operateModeDisable() {
      return (!this.hasChoosePlatformType && !this.isEdit);
    },
    // 其他运营人员
    accountOperationDisable() {
      return !this.hasChoosePlatformType && !this.isEdit || !this.hasoperateMode || this.isNeedDisabled(this.accountOperationObj);
    },
    accountOperationRequired() {
      return !this.hasoperateMode || !this.hasChoosePlatformType || this.isNeedRequired(this.accountOperationObj);
    },
    accountOperationRules() {
      return this.accountOperationRequired ? { required: true, trigger: 'change', validator: this.validateNumberEmpty('请选择其他运营人员') } : null;
    },
    // 所属经营体
    attributionMatrixDisable() {
      return !this.hasChoosePlatformType && !this.isEdit || !this.hasoperateMode || this.isNeedDisabled(this.attributionMatrixObj);
    },
    attributionMatrixRules() {
      return !this.hasoperateMode || !this.hasChoosePlatformType || this.isNeedRequired(this.attributionMatrixObj) ? { required: true, trigger: 'change', validator: this.validateEmpty('请选择所属经营体') } : null;
    },
    // 合作运营方
    cooperationObjDisable() {
      return (!this.hasChoosePlatformType && !this.isEdit || !this.hasoperateMode || this.isNeedDisabled(this.cooperationObj));
    },
    cooperationObjRules() {
      return this.isNeedRequired(this.cooperationObj) ? { required: true, trigger: 'change', validator: this.validateEmpty('请选择合作运营方') } : null;
    },
    // 是否挂靠
    microTaskDisable() {
      return !this.hasChoosePlatformType;
    }
  },
  watch: {
    'editResouceForm.platformType': {
      handler: function(newVal, oldVal) {
        if (newVal !== oldVal) {
          !this.initCreate && this.resetForm();
          this.setMistaskTip(newVal);// 挂靠提示
          this.setLinkDisable(newVal);// 调整字段禁用
          this.platformDesc = newVal === 5 ? '自动采集更新：账号、粉丝量、赞与收藏' : '自动采集更新：账号、粉丝量';
        }
      },
      deep: true
    },
    'editResouceForm.operateMode': {
      handler: function(newV, oldV) {
        this.setOperateDisable(newV);// 设置运营模式相关字段的禁用及是否必填
        this.operateModeChange(!newV && oldV);
      },
      deep: true
    },
    // 监听是否已存在资源，切换不同提示
    hasResourceData: {
      handler: function(newV) {
        this.hasResourceType = 0;
        if (newV.type === 3) { this.isLinkMatch = newV.isLinkMatch; }
        if (newV[this.checkValue[`${newV.type}`]]) {
          this.hasResourceType = newV.type;
        }
      },
      deep: true
    }
  },
  methods: {
    isNodeIdExistInTree,
    hasRouteAuth,
    getPlatformList() {
      platformList().then(({ code, data }) => {
        this.platformList = data;
      });
    },
    getOperateoptions() {
      return new Promise((resolve, reject) => {
        getOperateoptions().then(res => {
          if (res.code === 200) {
            this.operateModeList = res.data;
            resolve(res);
          }
        });
      });
    },
    getSupplier() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          getSupplierList({ onlyChannel: true, ...params }).then(res => {
            const data = res;
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    platformTypeChange(platformId) {
      this.$set(this.editResouceForm, 'autoPick', false);
      this.$nextTick(() => {
        this.$refs.createSignAccountInfo && this.$refs.createSignAccountInfo.getDynamic(this.editResouceForm);
      });
    },
    // 获取label的值
    getPlatformLabel(value) {
      if (!value) { return; }
      let obj = {};
      obj = this.platformList.find(item => {
        return item.id === value;
      });
      this.platformTypeName = obj.value;
    },
    // 是否是采集平台
    isPlatformFit() {
      !this.isEdit && this.getPlatformLabel(this.editResouceForm.platformType);
      const platformTypeName = !this.isEdit ? this.platformTypeName : this.editResouceForm.platformTypeName;
      return PICK_PLATFORM.includes(platformTypeName);
    },
    autoPickChange(val) {
      if (!this.editResouceForm.platformType && !this.isEdit) {
        this.$message.error('请选择平台');
        this.editResouceForm.autoPick = false;
        return;
      }
      if (!this.isPlatformFit()) {
        this.editResouceForm.autoPick = false;
        this.$message.warning('该平台暂无采集功能，如需要请联系研发部');
      }
      this.$forceUpdate();
    },
    selectSupplier(val) {
      this.editResouceForm.cooperation = val;
    },
    // 清空除下单平台其他字段
    resetForm() {
      if (this.$refs.editResouceForm) {
        const fields = this.$refs.editResouceForm.fields;
        fields.forEach(e => {
          if (e.prop !== 'platformType') {
            e.resetField();
          }
        });
      }
    },
    operateModeChange(isClearMode = false) {
      if (!this.$refs.editResouceForm) return;
      const fields = this.$refs.editResouceForm.fields;
      const props = ['accountOperation', 'attributionMatrix', 'cooperationObj', 'supplierType'];
      const fieldConfig = {
        'accountOperation': this.accountOperationObj,
        'attributionMatrix': this.attributionMatrixObj,
        'cooperationObj': this.cooperationObj,
        'supplierType': this.cooperationObj
      };
      fields.forEach(e => {
        if (props.includes(e.prop)) {
          e.clearValidate();
          const isDisabled = this.isNeedDisabled(fieldConfig[e.prop]);
          if (isDisabled || isClearMode) {
            e.resetField();
          }
          // 编辑时回填非禁用字段
          if (!isDisabled && this.hasoperateMode && this.isEdit) {
            this.$set(this.editResouceForm, e.prop, this.editDefaultData[e.prop]);
          }
        }
      });
    },
    // 挂靠提示
    setMistaskTip(platformType) {
      this.microTaskTip = this.tips[getPlatformTypeName(platformType, this.platformList)] || '';
      this.$set(this.editResouceForm, 'platformType', platformType);
      if (!this.microTaskTip && this.hasChoosePlatformType && !this.isEdit) {
        this.$set(this.editResouceForm, 'microTask', 0);
      }
    },
    // 设置链接字段是否禁用
    setLinkDisable(platformType) {
      this.linkDisable = false;
      if (this.isEdit && this.editResouceForm) {
        if (this.editResouceForm.platformTypeName === '微信视频号') {
          this.linkDisable = true;
          return;
        }
      }
      if (getPlatformTypeName(platformType, this.platformList) === '微信视频号') {
        this.linkDisable = true;
      }
    },
    // 随运营模式切换字段禁用状态和是否必填
    setOperateDisable(val) {
      let options = [];
      const optionName = getOperateModeName(val, this.operateModeList);
      switch (optionName) {
        case '飞博自营': {
          options = [
            { isRequired: true, isDisabled: false },
            { isRequired: true },
            { isRequired: false, isDisabled: true }
          ];
          break;
        }
        case '达人合作+自营': {
          options = [
            { isRequired: true, isDisabled: false },
            { isRequired: true },
            { isRequired: true, isDisabled: false }
          ];
          break;
        }
        case '委外运营':
        case '独家代理':
        case '非独家代理': {
          options = [
            { isRequired: false, isDisabled: false },
            { isRequired: true },
            { isRequired: true, isDisabled: false }
          ];
          break;
        }
        case '商务合作': {
          options = [
            { isRequired: false, isDisabled: false },
            { isRequired: true },
            { isRequired: false, isDisabled: false }
          ];
          break;
        }
        default: {
          options = [
            { isRequired: false, isDisabled: false },
            { isRequired: false },
            { isRequired: false, isDisabled: false }
          ];
          break;
        }
      }
      this.setRequiredAndDisable(options);
      if (!this.isEdit && this.hasChoosePlatformType) { this.setDefalutValue(optionName); }
    },
    // 信息校验
    resourceInputCheck(value, type) {
      const params = {
        resourceName: '',
        resourceId: '',
        resourceLink: '',
        type,
        id: this.resourceId,
        platformType: this.editResouceForm.platformType
      };
      switch (type) {
        case 1:params.resourceName = value.trim(); break;
        case 2:params.resourceId = value; break;
        case 3:params.resourceLink = value.trim(); break;
        default:break;
      }
      if (type === 1 && value.length <= 2) return;
      this.setResource(params, type);
    },
    // 路由参数处理
    setResource(params, type) {
      hasResource(params).then((res) => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.hasResourceData = res.data;
        if (!res.data[this.checkValue[`${type}`]]) {
          return;
        }
        const routeParams = {
          activeTabs: this.getActiveTabs(this.editResouceForm.platformType),
          platformType: this.editResouceForm.platformType
        };
        Object.keys(res.data).forEach(el => {
          if (res.data[el]) {
            routeParams[el] = res.data[el];
          }
        });
        // 资源账号
        if (type === 1) {
          routeParams['resourceName'] = params.resourceName;
        }
        this.routeParams = routeParams;
      }).catch((err) => {
        console.log(err);
      });
    },
    // 快速查看
    quickFindResource() {
      const routeUrl = this.$router.resolve({
        name: 'resource',
        query: this.routeParams
      });
      window.open(routeUrl.href, '_blank');
    },
    // 获取资源列表页对应的label值和平台的值
    getActiveTabs(platformType) {
      let activeTabs = '';
      if (!platformType) return;
      const zhiboArr = ['微博直播', '淘宝直播', '小红书直播', '抖音直播'];
      switch (getPlatformTypeName(platformType, this.platformList)) {
        case '抖音':activeTabs = '4'; break;// 抖音
        case '微博':activeTabs = '2'; break;// 微博
        case '微信':activeTabs = '1'; break;// 微信
        case '小红书':activeTabs = '3'; break;// 小红书
        case 'B站':activeTabs = '7'; break;// B站
        default:activeTabs = '5'; break;// 更多
      }
      if (zhiboArr.includes(getPlatformTypeName(platformType, this.platformList))) {
        activeTabs = '6';
      }
      return activeTabs;
    },
    validateTrim(msg, type) { // type 1账号 2账号id 3链接
      return (rule, value, callback) => {
        this.hasResourceType = 0;
        this.isLinkMatch = true;
        if (!value || !value.trim()) {
          callback(new Error(msg));
        } else {
          if (this.isSave) { // 保存触发的表单校验不去验证输入的资源信息
            callback();
            return;
          }
          this.resourceInputCheck(value, type);
          callback();
        }
      };
    },
    validateEmpty(msg) {
      return (rule, value, callback) => {
        this.hasResourceType = 0;
        this.isLinkMatch = true;
        if (!value || value === '') {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    },
    validateNumberEmpty(msg) {
      return (rule, value, callback) => {
        this.hasResourceType = 0;
        this.isLinkMatch = true;
        if (value === null || value === '' || value.length === 0) {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    },
    // 是否必填
    isNeedRequired(obj = {}) {
      return obj.state && obj.state.isRequired;
    },
    // 是否禁用
    isNeedDisabled(obj = {}) {
      return obj.state && obj.state.isDisabled;
    },
    // 设置字段禁用及是否必填
    setRequiredAndDisable(options) {
      this.$set(this.accountOperationObj, 'state', options[0]);
      this.$set(this.attributionMatrixObj, 'state', options[1]);
      this.$set(this.cooperationObj, 'state', options[2]);
    },
    // 设置默认值
    setDefalutValue(optionName = '') {
      const optionNames = ['委外运营', '独家代理', '非独家代理', '商务合作'];
      if (this.accountOperationObj && this.accountOperationObj.state.isRequired && !this.accountOperationObj.state.isDisabled) {
        this.$set(this.editResouceForm, 'accountOperation', [this.userInfo.id]);
      }
      if (optionNames.includes(optionName)) {
        this.$set(this.editResouceForm, 'accountOperation', [this.userInfo.id]);
      }
      this.defaultUserList = [{ id: this.userInfo.id, userName: this.userInfo.userName }];
      this.$set(this.editResouceForm, 'attributionMatrix', this.userInfo.currentDeptIds[0]);
    },
    // 获取部门列表
    queryDeptTreeList(sort = false) {
      return new Promise((resolve, reject) => {
        getDepartmentAll().then(res => {
          if (res.code === 200) {
            this.deptTreeList = (res && res.data) || [];
            if (sort) cascaderSoft(this.cooperationDepartment, this.deptTreeList);
            resolve(res);
          }
        });
      });
    },
    goCreateSupplier() {
      if (!this.hasRouteAuth('medium:supplier:edit')) {
        this.$message.error('暂无供应商新建权限！');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    setOldData(data) {
      this.oldData = JSON.parse(JSON.stringify(data));
    },
    updateFollowUsers(list) { // 同步执行经纪/达人运营人员至跟进人字段
      const users = _.cloneDeep(this.editResouceForm.followUsers) || [];
      const appendUsers = list.filter(item => users.every(user => user.id !== item.id));
      this.$set(this.editResouceForm, 'followUsers', [...users, ...appendUsers]);
    },
    update(data) {
      if (data.id) {
        this.editResouceForm.cooperationObj = {
          supplierName: data.name,
          supplierId: data.id,
          supplierType: data.supplierType === 0 ? 1 : 0
        };
        // 这里的供应商类型与销售供应商类型是相反的，应该是创建这个页面的时候没有去销售供应商检查，后续注意
        // 正确的是 supplierType 0:客户  1:公司
        // 这里的是 supplierType 0:公司  1:客户
        this.suppliersChange(this.editResouceForm.cooperationObj);
      }
    },
    // 获取所有标签
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      });
    },
    suppliersChange(val) {
      this.$set(this.editResouceForm, 'cooperation', val.supplierName);
      this.$set(this.editResouceForm, 'supplierType', val.supplierType);
    },
    clearSupplier() {
      this.$set(this.editResouceForm, 'cooperationObj', null);
      this.$set(this.editResouceForm, 'cooperation', '');
      this.$forceUpdate();
    }
  }
};
